package org.yi.utils;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * Http相关工具方法
 * @author qq
 *
 */
public class HttpUtils {
	
	/**
	 * 获取访问用户的真实ip（包括用户使用多级代理或者反向代理时的真实ip）
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request){
	   
       String ip = request.getHeader("x-forwarded-for");
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("WL-Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getRemoteAddr();
       }
       return ip; 
	}

	/**
	 * get request domain
	 * @param request
	 * @return
	 */
	public static String getBaseDomain(HttpServletRequest request) {
		return request.getServerName();
	}

	/**
	 * get full request url
	 * @param request
	 * @return
	 */
	public static String getFullUrl(HttpServletRequest request) {
		StringBuffer queryString = new StringBuffer();
		if("GET".equalsIgnoreCase(request.getMethod())) {
			queryString.append(StringUtils.isBlank(request.getQueryString()) ? "" : "?"+request.getQueryString());
		}
		Map<String, String[]> params = request.getParameterMap();
		if(params != null && params.size() > 0) {
			if(queryString.length() > 0) {
				queryString.append("&request_method=").append(request.getMethod()).append("&");
			} else {
				queryString.append("?request_method=").append(request.getMethod()).append("&");
			}
			for (String key : params.keySet()) {
				String[] values = params.get(key);
				for (int i = 0; i < values.length; i++) {
					String value = values[i];
					if(StringUtils.isNotEmpty(value)) {
						queryString.append(key + "=" + value + "&");
					}
				}
			}
			// 去掉最后一个空格
			queryString = queryString.deleteCharAt(queryString.length() - 1);
		}
		
		return request.getScheme() + "://"
			 + request.getServerName() + ":" 
			 + request.getServerPort() 
			 + request.getRequestURI()
			 + queryString;
	}
}
